package top.malaoshi.netdisk.component;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.malaoshi.netdisk.Constant;
import top.malaoshi.util.StringUtil;
import top.malaoshi.web.utils.ConfigReader;
import top.malaoshi.web.utils.PathUtils;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

@Component
@Order(100)
public class NetdisConfigReader {
    private Map configMap;
    private String dbPath;
    public NetdisConfigReader() throws IOException {
        ConfigReader configReader = new ConfigReader(Constant.CONFIG);

        configMap = configReader.read();
        String urlOfConfig = (String) configMap.get("url");
        if(urlOfConfig.contains("${classes}")) {
            URL fileURL = this.getClass().getResource("/");
            String path = fileURL.getPath();
            dbPath = StringUtil.slice(path,0,-1);
            String newURL = urlOfConfig.replace("${classes}", dbPath);
            configMap.put("url", newURL);
        }else if(urlOfConfig.contains("${WEB-INF}")) {
            dbPath = PathUtils.getWebInfPath().getAbsolutePath();
            String newURL = urlOfConfig.replace("${WEB-INF}", dbPath);
            configMap.put("url", newURL);
        }
    }

    public Map getConfigMap() {
        return configMap;
    }

    public String getDbPath() {
        return dbPath;
    }
}
